﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Xejen.Database.Dapper
{
    /// <inheritdoc cref="IUnitOfWork"/>
    public class UnitOfWork<TDbContext> : IUnitOfWork
        where TDbContext : IDbConnection
    {
        private readonly TDbContext _dbContext;
        private IDbTransaction _transaction;

        /// <inheritdoc cref="UnitOfWork{TDbContext}"/>
        public UnitOfWork(IDbContextProvider<TDbContext> provider)
        {
            _dbContext = provider.GetDbContext();
        }

        /// <inheritdoc/>
        public void BeginTransaction()
        {
            if (_dbContext.State != ConnectionState.Open)
            {
                _dbContext.Open();
            }
            _transaction = _dbContext.BeginTransaction();
        }

        /// <inheritdoc/>
        public void Commit()
        {
            _transaction?.Commit();
        }

        /// <inheritdoc/>
        public void Rollback()
        {
            _transaction?.Rollback();
        }

        /// <inheritdoc/>
        public void Dispose()
        {
            _transaction?.Dispose();
            _transaction = null;
            //_dbContext.Dispose();
        }
    }
}
